package com.lee.nio.channel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * NIOFileChannel02
 * 读文件
 *
 * @author dralee
 * @date 2021-12-28 23:10:43
 **/
public class NIOFileChannel02 {
    public static void main(String[] args) throws IOException {

        // 创建文件输入流
        File file = new File("file1.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        // 通过fileInputStream获取对应FileChannel ->实际类型 FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();
        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        // 将 通道数据读入byteBuffer
        fileChannel.read(byteBuffer);
        //  将byteBuffer字节数据转成String
        System.out.println(new String(byteBuffer.array(), StandardCharsets.UTF_8));
    }
}
